package com.hue.nio.day02.two;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/*
    客户端的写线程
 */
public class ClientWriteThread implements Runnable {
    private SocketChannel socketChannel;

    public ClientWriteThread(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        Scanner sc = new Scanner(System.in);
        ByteBuffer buffer = ByteBuffer.allocate(512);
        while (true) {
            String line = sc.nextLine();
            buffer.put(line.getBytes());
            buffer.flip();
            try {
                socketChannel.write(buffer);
                buffer.clear();
            } catch (IOException e) {
                try {
                    socketChannel.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
